#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFile>
#include <QMessageBox>
#include <QFileInfoList>
#include <ctime>
#include <QDebug>
#include <QRandomGenerator>
#include <QTextStream>
#include <QTextCodec>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    checkupnext=false;
    init();
    //setFixedSize(800,600);
    setbackground();
    // 连接播放器信号到进度条更新
  //  connect(m_player,&QMediaPlayer::positionChanged)



  connect(ui->startButton,&QPushButton::clicked,this,&MainWindow::handlebutton);
    connect(ui->circleButton,&QPushButton::clicked,this,&MainWindow::changemodel);
    connect(ui->downButton,&QPushButton::clicked,this,&MainWindow::nextsong);
    connect(ui->upButton,&QPushButton::clicked,this,&MainWindow::upsong);
    connect(m_player,&QMediaPlayer::durationChanged,this,&MainWindow::totaltime);
    connect(m_player,&QMediaPlayer::positionChanged,this,&MainWindow::curtime);

    connect(m_player, &QMediaPlayer::positionChanged, this, &MainWindow::updateLyricDisplay);
    connect(m_player, &QMediaPlayer::mediaStatusChanged, this, &MainWindow::handleMediaStatusChange);//状态改变下一首歌

    connect(ui->listWidget,&QListWidget::itemDoubleClicked,ui->listWidget,&QListWidget::itemChanged);//
    //connect(ui->listWidget,&QListWidget::itemDoubleClicked,this,&MainWindow::handlebutton);//图腾变化
    connect(ui->listWidget,&QListWidget::itemChanged,this,&checkchangesong);
    //ui->listWidget->hide();
    //this->winlayout->addWidget(ui->target);
    //this->winlayout->addLayout(ui->lowLayout);
    //this->setLayout(winlayout);
    // 更精确的连接方式



   srand(time(NULL));
   showsongword();
}
void MainWindow::checkchangesong(QListWidgetItem *item)
{

    qDebug()<<"checkchangesong:" <<item->text();
    QString songname=item->text();
    QString loadurl=musicurl+"\\"+songname+".mp3";
    qDebug()<<loadurl;
    m_player->setMedia(QUrl::fromLocalFile(loadurl));
    totaltimes=m_player->duration();
    ui->progress->setRange(0, totaltimes);
    ui->ingtimelable->setText(QString::number(0));
    ui->totaltimelable->setText(QString::number(totaltimes));
    // ui->progress->setEnabled(true);
    m_player->play();
    showsongword();
    star=true;
    ui->startButton->setIcon(QIcon(":/icon/stop1.png"));
}





void MainWindow::handleMediaStatusChange(QMediaPlayer::MediaStatus status) {
    if (status == QMediaPlayer::EndOfMedia) {
        nextsong();
    }
}


//设置进度条总时间
void MainWindow::totaltime(qint64 duration){
    ui->totaltimelable->setText(QString::number(duration));
    total=duration;
    ui->progress->setRange(0, static_cast<int>(duration));
    qint64 totalMinutes = duration / 60000;  // 1分钟 = 60,000毫秒
    qint64 remainder = duration % 60000;

    // 分解剩余部分为秒和毫秒
    int seconds = remainder / 1000;        // 秒
    int milliseconds = remainder % 1000;
    QString timeTex = QString("%1:%2")
                           .arg(totalMinutes)
                           .arg(seconds, 2, 10, QLatin1Char('0'));
    ui->totaltimelable->setText(timeTex);

    //qDebug()<<duration<<"1111 ";
}
//设置进度条当前时间
void MainWindow::curtime(qint64 position)
{

    qint64 totalMinutes = position / 60000;  // 1分钟 = 60,000毫秒
    qint64 remainder = position % 60000;

    // 分解剩余部分为秒和毫秒
    int seconds = remainder / 1000;        // 秒
    int milliseconds = remainder % 1000;
    QString timeTex = QString("%1:%2")
                           .arg(totalMinutes)
                           .arg(seconds, 2, 10, QLatin1Char('0'));
   // ui->totaltimelable->setText(timeTex);
    ui->ingtimelable->setText(timeTex);
    changepositionprocebar(position);
}
//歌词显示高亮
void MainWindow::updateLyricDisplay(qint64 position)
{
        if (v.isEmpty()) return;

        // 查找当前应显示的歌词行
        int newIndex = -1;
        for (int i = 0; i < v.size(); ++i) {
            if (v[i].time <= position) {
                newIndex = i;
            } else {
                break;
            }
        }

        // 如果找到新行且与当前显示不同
        if (newIndex != -1 && newIndex != currentLyricIndex) {
            currentLyricIndex = newIndex;
            highlightCurrentLyric();

        }

}

void MainWindow::changepositionprocebar(qint64 curpos)
{
     ui->progress->setValue(curpos);
}
//当前行高亮
void MainWindow::highlightCurrentLyric()
{
    for (int i = 0; i < ui->songwordwidgetlist->count(); ++i) {
        ui->songwordwidgetlist->item(i)->setBackground(Qt::transparent);
        ui->songwordwidgetlist->item(i)->setForeground(Qt::black);
    }

    // 高亮当前行
    if (currentLyricIndex >= 0 && currentLyricIndex < ui->songwordwidgetlist->count()) {
        highlightCurrentLyric(currentLyricIndex);
        // auto item = ui->songwordwidgetlist->item(currentLyricIndex);
        // item->setBackground(QColor("#4A90E2"));
        // item->setForeground(Qt::white);
    }
}
void MainWindow::highlightCurrentLyric(int index) {
    // 重置所有行样式

    for (int i = 0; i < ui->songwordwidgetlist->count(); ++i) {
        QListWidgetItem* item = ui->songwordwidgetlist->item(i);
        item->setForeground(QColor("#888888"));

        QFont font = item->font();
        font.setBold(false);
        font.setPointSize(14);
        item->setFont(font);
    }

    // 高亮当前行
    if (index >= 0 && index < ui->songwordwidgetlist->count()) {
        QListWidgetItem* currentItem = ui->songwordwidgetlist->item(index);

        currentItem->setForeground(QColor("#4A90E2"));

        //currentItem->setBackgroundColor(QColor(255, 0, 0));
        //currentItem->setTextColor(QColor(255, 0, 0));
        QFont font = currentItem->font();
        font.setBold(true);
        font.setPointSize(18);

        currentItem->setFont(font);
        //currentItem->setForeground(Qt::yellow);
        // 滚动到当前行
        ui->songwordwidgetlist->scrollToItem(currentItem, QAbstractItemView::PositionAtCenter);
    }
}



MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::init()
{



    m_player=new QMediaPlayer(this);
   // m_player->setMedia(QUrl::fromLocalFile("D:\\qtstudey\\music\\music\\mp3\\等一分钟_徐誉滕.mp3"));  //qt6已经移除

    ui->setupUi(this);
    //ui->progress->setMinimum(0);
    //ui->progress->setMaximum(100);
    this->setWindowTitle("叼炸天音乐播放器");
    this->setWindowIcon(QIcon(":/icon/music.png"));

    this->initbuticon(ui->circleButton,":/icon/order.png");
    this->initbuticon(ui->upButton,":/icon/front.png");
    this->initbuticon(ui->downButton,":/icon/next.png");
    this->initbuticon(ui->startButton,":/icon/start.png");
    this->initbuticon(ui->listButton,":/icon/list.png");
    musicurl="D:\\qtstudey\\music\\music\\mp3";
    showmusiclist(musicurl);
    model=ORDER;
    ui->listWidget->setCurrentRow(0);
}

void MainWindow::setbackground()
{
    // QPixmap pix(url);
    // if(pix.isNull()){
    //     qDebug<<"背景图片加载失败\n";
    // }else{

    //ui->listWidget->setStyleSheet("QWidget { background-image: url(:/image/background.jpg); }");
        // ui->target->setStyleSheet("QWidget { background-image: url(:/image/background.jpg); }");
        // ui->lowwidget->setStyleSheet("background-color: #2ecc71;");
        // ui->listWidget->setStyleSheet("background-color: #2E2E2E; border: none;border-radius:20px");

    //}


    ui->listWidget->setStyleSheet(R"(
        QListWidget {
            background: rgba(30, 30, 40, 0.8);
            border: 1px solid #444;
            border-radius: 8px;
            padding: 5px;
            font-size: 12px;
        }
        QListWidget::item {
            color: #DDDDDD;
            height: 36px;
            border-bottom: 1px solid rgba(255,255,255,0.05);
            padding-left: 15px;
        }
        QListWidget::item:hover {
            background: rgba(74, 144, 226, 0.3);
        }
        QListWidget::item:selected {
            background: rgba(74, 144, 226, 0.7);
            color: white;
            border-radius: 4px;
        }
    )");

    ui->songwordwidgetlist->setStyleSheet(R"(
QListWidget {
        background: rgba(40, 40, 50, 0.7);
        border-radius: 10px;
        border: 1px solid rgba(255, 255, 255, 0.1);
        padding: 5px;
        font-size: 12px;
        color: #EEEEEE;
    }
        QListWidget {
            background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                stop:0 #1E1E2A, stop:1 #323246);
            border: none;
            font-family: "Microsoft YaHei";
            font-size: 14pt;
        }
        QListWidget::item {
            color: #AAAAAA;
            height: 60px;
            text-align: center;
            background: transparent;
            border: none;
        }
        QListWidget::item:selected {
            color: #4A90E2;
            font-size: 18pt;
            font-weight: bold;
        }
    )");
   // ui->songwordwidgetlist
}

void MainWindow::initbuticon(QPushButton *but, QString url)
{
    but->setFixedSize(50,50);
    QIcon icon(url);
    //按钮设置图标");
    if(icon.isNull()) {
        qDebug() << "无法加载图标，88888使用默认图标";
        // icon = QIcon(":/default/icon"); // 备用图标
    }else{
    qDebug() << "111无法加载图标，88888使用默认图标";
    but->setIcon(icon);
    but->setIconSize(QSize(but->width(),but->height()));
    but->setStyleSheet("QPushButton { border: none;}");
    }
}
//加载歌词
void MainWindow::showmusiclist(const QString &dirpath)
{
    QDir dir(dirpath);
    if(!dir.exists()){
        QMessageBox::information(ui->listWidget,"musicfile dir","file no exists");
        return;
    }
    QFileInfoList filelist=dir.entryInfoList(QDir::Files);
    for(auto i:filelist){
        if(i.suffix()=="mp3"){
            ui->listWidget->addItem(i.baseName());
        }
    }
}

void MainWindow::startplaymusic()
{

   auto item= ui->listWidget->currentItem();
    qDebug()<< item->text();
   QString songname=item->text();
    QString loadurl=musicurl+"\\"+songname+".mp3";
   qDebug()<<loadurl;
    m_player->setMedia(QUrl::fromLocalFile(loadurl));
    totaltimes=m_player->duration();
    ui->progress->setRange(0, totaltimes);
    ui->ingtimelable->setText(QString::number(0));
    ui->totaltimelable->setText(QString::number(totaltimes));
   // ui->progress->setEnabled(true);
    m_player->play();
    showsongword();
}

void MainWindow::showsongword()
{
    ui->songwordwidgetlist->clear();
    QString filename=ui->listWidget->currentItem()->text();
    QString url;
    url=musicurl+"\\"+filename+".lrc";
    qDebug()<<url;
    QFile file(url);
    bool ok=file.open(QIODevice::ReadOnly);
    if(!ok){
        qDebug()<<"file open error";
        return;
    }
    QTextStream in(&file);
    in.setCodec("UTF-8");  // 优先尝试UTF-8
    if (in.codec()->name() != "UTF-8") {
        in.setCodec("GB18030");  // 中文系统常见备选编码
    }
    QString line;
    int currow=-1;
    while(!in.atEnd()){
        line=in.readLine();
        //[00:00.00]
        int time=line.mid(1,2).toInt()*60000+line.mid(4,2).toInt()*1000+line.mid(7,2).toInt()*10;
        qDebug()<<"time"<<time<<line.mid(0,2);
        //songtimelist.append(time);
        line.remove(0,10);
        ui->songwordwidgetlist->addItem(line);
        v.push_back({time,line,currow++});
    }
    file.close();
   // nextsong();
    // for(auto i:songtimelist)
    //     qDebug()<<i<<"\n";
}



void MainWindow::changemodel()
{
    //改变当前模式和图标
    if(model== ORDER){
        model= RAND;
        ui->circleButton->setIcon(QIcon(":/icon/rand.png"));
    }else{
        model=ORDER;
         ui->circleButton->setIcon(QIcon(":/icon/order.png"));
    }
}
//按键图腾变换
void MainWindow::handlebutton()
{
    if(status==0){//第一次按下star song
        status++;
        if(checkupnext=true){//是next or up song 时不调用函数startplaymusic();他们里面有调用
            checkupnext=false;
        }else{
            startplaymusic();
        }

        star=true;
        ui->startButton->setIcon(QIcon(":/icon/stop1.png"));
    }else{
    if(star==false){
        star=true;
        ui->startButton->setIcon(QIcon(":/icon/stop1.png"));
        m_player->play();
        //startplaymusic();
    }else{
        star=false;
        ui->startButton->setIcon(QIcon(":/icon/start.png"));
        m_player->pause();
    }
    }
}
//切换下一首
void MainWindow::nextsong()
{
    checkupnext=true;
    v.clear();
    currentLyricIndex = -1;
    int cur=ui->listWidget->currentRow();
    int next=0;
    int count = ui->listWidget->count();
    if(count==0)return;
    if(model==ORDER) {
        next=(cur+1)%count;
        qDebug() << count<<next;
    }else{
        do {
            next=rand()%count;
            //next = QRandomGenerator::global()->bounded(count); // 生成0到count-1的随机数
        } while (next == cur );
        qDebug() << next;
    }
    ui->listWidget->setCurrentRow(next);
    startplaymusic();
    showsongword();
    ui->startButton->setIcon(QIcon(":/icon/stop1.png"));

}
//切换上一首
void MainWindow::upsong()
{
    checkupnext=true;
    currentLyricIndex = -1;
    v.clear();
    int cur=ui->listWidget->currentRow();
    int up=0;
    int count = ui->listWidget->count();
    if(count==0)return;
    if(model==ORDER) {
        up=cur-1;
        if(up<0){
            up=count-1;
        }
        qDebug() << count<<up;
    }else{
        do {
            up=rand()%count;
            //next = QRandomGenerator::global()->bounded(count); // 生成0到count-1的随机数
        } while (up == cur );
        qDebug() << up;
    }
    ui->listWidget->setCurrentRow(up);
    startplaymusic();
    showsongword();
    ui->startButton->setIcon(QIcon(":/icon/stop1.png"));
}
